﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;

namespace Print_UI
{
    public partial class FrmCreateGeneralSchoolFee : CommonForm
    {
        #region Contructors
        public FrmCreateGeneralSchoolFee()
        {
            InitializeComponent();
        }
        #endregion

        #region Private members
        
        //Load Department List
        private void LoadDeparment()
        {
            try
            {
                if (checkLogin(UserName))
                {

                    var departmentAdmin = from obj in Model.CAT_Department.OrderBy(c => c.Name)
                                          select obj;
                    Dictionary<int, string> dicAdmin = new Dictionary<int, string>();
                    dicAdmin.Add(-1, "----Chọn Khoa----");
                    foreach (var item in departmentAdmin)
                    {
                        dicAdmin.Add(item.ID, item.Name);

                    }
                    cboDepartment.Properties.ValueMember = "Key";
                    cboDepartment.Properties.DisplayMember = "Value";
                    cboDepartment.Properties.DataSource = dicAdmin;
                    cboDepartment.EditValue = -1;
                }
                else
                {
                    var departmentUser = from obj in Model.CAT_Department.Where(c => c.ID == DepartmentID)
                                         select obj;
                    Dictionary<int, string> dicUer = new Dictionary<int, string>();
                    foreach (var item in departmentUser)
                    {
                        dicUer.Add(item.ID, item.Name);

                    }
                    cboDepartment.Properties.ValueMember = "Key";
                    cboDepartment.Properties.DisplayMember = "Value";
                    cboDepartment.Properties.DataSource = dicUer;
                    cboDepartment.EditValue = departmentUser.FirstOrDefault().ID;
                    cboDepartment.Enabled = false;
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
         
        }

        //Load list of sector follow deparment
        private void LoadSector()
        {
          
            
                int i = Convert.ToInt32(cboDepartment.EditValue);
                var Sector = from p in Model.CAT_Department
                             join k in Model.CAT_Sector on p.ID equals k.DepartmentID
                             where i == k.DepartmentID
                             select new { k.ID, k.Name };
                Dictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(-1, "--- Chọn Ngành ---");
                foreach (var item in Sector)
                {
                    dic.Add(item.ID, item.Name);
                }
                cboSector.Properties.ValueMember = "Key";
                cboSector.Properties.DisplayMember = "Value";
                cboSector.Properties.DataSource = dic;
                cboSector.EditValue = -1;
  
        }
       
       
       

        //Load Auth
        private void LoadAuth()
        {

            if (Actions != null)
            {
                if (Actions.Contains("Add"))
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                else
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                if (Actions.Contains("Edit"))
                {
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    AcceptButton = btnSave;
                }
                else
                {
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnSave.Visible = false;
                    AcceptButton = null;
                }

                //if (Actions.Contains("Del"))
                //    btnDelete.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                //else
                //    btnDelete.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }
        }

        //Check Auth
        private void CheckAuth(string key)
        {
            if (Actions != null && Actions.Contains(key))
            {
                if (key == "Add")
                {
                    btnSave.Visible = true;
                    AcceptButton = btnSave;
                    return;
                }
                else
                {
                    btnSave.Visible = false;
                    AcceptButton = null;
                }

                if (key == "Edit")
                {
                    btnSave.Visible = true;
                    AcceptButton = btnSave;
                    return;
                }
                else
                {
                    btnSave.Visible = false;
                    AcceptButton = null;
                }
            }
        }

        //Load data follow user
        private void LoadData()
        {
            var query = from obj in Model.PRI_SchoolFeeSetting
                        join obj1 in Model.CAT_Year on obj.YearID equals obj1.ID
                        join obj2 in Model.CAT_Sector on obj.SectorID equals obj2.ID
                        join obj3 in Model.CAT_Sector on obj.SectorID equals obj3.ID
                        where obj3.DepartmentID == DepartmentID
                        select new
                        {
                            ID = obj.ID,
                            YearName = obj1.Course,
                            SectorName = obj2.Name,
                            DayModified = obj.ModifiedDate,
                            fee = obj.SchoolFee,
                         //   SemsterID = obj.SemsterID
                        };  
                     
            gvData.DataSource = query;
            gridColumn3.DisplayFormat.FormatString = "{0:#,###.##}";
            gridColumn3.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
        }
        
        //Check data when user create schoolfee
        private bool CheckInput()
        {
            bool result = true;
            int year = Convert.ToInt32(cboYear.EditValue);
           // int semester = Convert.ToInt32(cboSemester.EditValue);
            int sector = Convert.ToInt32(cboSector.EditValue);
            
            dxErrorProvider1.ClearErrors();

                
               
            //Check schoole fee exist
                if (Model.PRI_SchoolFeeSetting.FirstOrDefault(c => c.ID != _id && c.YearID == year
                    && c.SectorID == sector) != null)
                {
                    CommonMessage("Đã tồn tại học phí này");
                    result = false;
                }
                else
                {
                    if (int.Parse(cboDepartment.EditValue.ToString()) == -1)
                    {
                        dxErrorProvider1.SetError(cboDepartment, "Chưa Chọn Khoa");
                        result = false;
                    }
                    if (txtFee.Text == "" || txtFee.Text == "0")
                    {
                        dxErrorProvider1.SetError(txtFee, "Chưa Nhập Giá Trị Học phí");
                        result = false;
                    }
                    if (int.Parse(cboSector.EditValue.ToString()) == -1)
                    {
                        dxErrorProvider1.SetError(cboSector, "Chưa Chọn Ngành");
                        result = false;
                    }
                    if (int.Parse(cboYear.EditValue.ToString()) == -1)
                    {
                        dxErrorProvider1.SetError(cboYear, "Chưa Chọn Năm Học");
                        result = false;
                    }

                    if (int.Parse(txtFee.Text) < -1)
                    {
                        dxErrorProvider1.SetError(txtFee, "Số tiền không hợp lệ");
                        result = false;
                    }
            
                }
            return result;
        }

        // check user Login
        private bool checkLogin(string UserName)
        {
            var user = from obj in Model.SYS_User.Where(c => c.UserName == UserName)
                       select obj;
            bool check = true;
            if (user.FirstOrDefault().IsAdmin == true)
            {
                return check;
            }
            else
            {
                check = false;
            }
            return check;
        }

        //Load School Year
        private void LoadSchoolYear()
        {
            var Year = (from p in Model.CAT_Year
                        join k in Model.PRI_SemesterSetting on p.ID equals k.YearID
                        where k.IsUsed == true
                        select new { p.ID, p.Course }).Distinct();
            Dictionary<int, int> dic = new Dictionary<int, int>();
            foreach (var item in Model.CAT_Year.OrderBy(c => c.Name))
            {
                dic.Add(item.ID, item.Course);
            }
            cboYear.Properties.ValueMember = "Key";
            cboYear.Properties.DisplayMember = "Value";
            cboYear.Properties.DataSource = dic;
            cboYear.EditValue = Year.FirstOrDefault().ID;

        }

        //private void LoadSchoolFee()
        //{
        //    int x = Convert.ToInt32(cboSector.EditValue);
        //    int y = Convert.ToInt32(cboYear.EditValue);
        //    //int z = Convert.ToInt32(cboSemester.EditValue);
        //    if (z == 1)
        //    {
        //        var n = from m in Model.PRI_SchoolFeeSetting
        //                 where x == m.SectorID && (y - 1) == m.YearID
        //                 && m.SemsterID == 2
        //                 select new { m.SchoolFee };
        //        txtFee.Text = n.ToString();      
        //    }
            
        //}

        private void Edit()
        {
            object cellValue = gridView1.GetFocusedRowCellValue("ID");
            if (cellValue != null)
            {
                CheckAuth("Edit");
                dxErrorProvider1.ClearErrors();
                pnMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Both;
                //txtKey.Enabled = false;
                _id = Convert.ToInt32(cellValue);
                var obj = Model.PRI_SchoolFeeSetting.FirstOrDefault(c => c.ID == _id);
                if (obj != null)
                {
                    txtFee.Text = obj.SchoolFee.ToString();
                    cboYear.EditValue = obj.YearID;
                    cboDepartment.EditValue = DepartmentID;
                    cboSector.EditValue = obj.SectorID;
                    //cboSemester.EditValue = obj.SemsterID;

                }
            }
        }



        #endregion
        
        #region Events
        
        //Load Form
        private void FrmCreateGeneralSchoolFee_Load(object sender, EventArgs e)
        {
            try
            {
                pnMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Both;
                // LoadAuth();
                LoadDeparment();
                LoadSector();
                LoadSchoolYear();
                LoadData();
              //  LoadSemester();
                
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        //Edit school fee
        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Edit();
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        //Delete School fee
        //private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    try
        //    {
        //        object cellValue = gridView1.GetFocusedRowCellValue("ID");
        //        if (cellValue != null)
        //        {
        //            int id = Convert.ToInt32(cellValue);
        //            int year = Convert.ToInt32(cboYear.EditValue);
        //            bool check = Model.PRI_SemesterSetting.Where(c => c.YearID == year && c.IsUsed == true).Count() > 0;
        //            if (check)
        //            {
        //                if (CommonConfirm("Bạn muốn xóa dữ liệu này?", "XÓA"))
        //                {
        //                    _id = -1;
        //                    pnMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
        //                    cboSector.EditValue = -1;
        //                    cboYear.EditValue = -1;
        //                    txtFee.Text = string.Empty;

        //                    var obj = Model.PRI_SchoolFeeSetting.FirstOrDefault(c => c.ID == id);
        //                    if (obj != null)
        //                    {
        //                        Model.DeleteObject(obj);
        //                        Model.SaveChanges();
        //                        CommonMessage("Xóa thành công");
        //                        LoadData();
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                CommonMessage("Năm học đang khóa không thể xóa");
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        CommonError(ex);
        //    }
        //}

        private void cboDepartment_EditValueChanged(object sender, EventArgs e)
        {
            LoadSector();
        }
        
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                pnMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
                txtFee.Text = string.Empty;
                cboYear.EditValue = -1;
                cboSector.EditValue = -1;

                _id = -1;
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        //Save School fee
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckInput())
                {
                    var obj = Model.PRI_SchoolFeeSetting.FirstOrDefault(c => c.ID == _id);
                    if (obj == null)
                    {
                        obj = new Main_Data.PRI_SchoolFeeSetting();
                        obj.ID = -1;
                        obj.SchoolFee = Convert.ToDecimal(txtFee.Text.ToString());
                        obj.CreatedDate = DateTime.Now;
                        obj.CreatedBy = UserName;
                    }
                    else
                    {
                        obj.ModifiedDate = DateTime.Now;
                        obj.ModifiedBy = UserName;
                    }

                    obj.YearID = Convert.ToInt32(cboYear.EditValue);

                    obj.SectorID = Convert.ToInt32(cboSector.EditValue);
                    obj.SchoolFee = Convert.ToDecimal(txtFee.Text.ToString());
                    //obj.SemsterID = Convert.ToInt32(cboSemester.EditValue);
                    if (_id == -1)
                        Model.AddToPRI_SchoolFeeSetting(obj);
                    Model.SaveChanges();

                    CommonMessage("Cập Nhật Thành Công");
                    pnMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
                    txtFee.Text = string.Empty;
                    
                    cboSector.EditValue = _id;
                    cboYear.EditValue = _id;
                  
                    _id = -1;
               
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        //Refresh 
        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                //RefreshModel();
                LoadData();


            }
            catch (Exception ex)
            {
                CommonError(ex);
            }


        }

        //Add new School fee
        private void btnAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                CheckAuth("Add");
                dxErrorProvider1.ClearErrors();
                pnMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Both;
                txtFee.Enabled = true;
                txtFee.Focus();
                txtFee.Text = string.Empty;
                cboSector.EditValue = _id;
                cboYear.EditValue = _id;
                //cboSemester.EditValue = _id;
                _id = -1;
           

            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                DevExpress.XtraGrid.Views.Grid.GridView view = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
                Point pt = view.GridControl.PointToClient(Control.MousePosition);
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = view.CalcHitInfo(pt);

                if (info.InRow || info.InRowCell)
                {
                    Edit();
                    //checkused();
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

       // Allow user enter numberic
        private void txtFee_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;

            }
        }
       
        private void cboYear_EditValueChanged(object sender, EventArgs e)
        {
            //LoadSemester();
          //  LoadSchoolFee();
          
            //checkused();
        }
        
  
        #endregion

        #region Private members
        private int _id = -1;
        #endregion

        private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            try
            {
                if (gridView1.RowCount > 0)
                {
                    GridView View = sender as GridView;
                    if (e.RowHandle >= 0)
                    {
                        object  obj = View.GetRowCellValue(e.RowHandle, View.Columns["DayModified"]);
                        if (obj != null && obj != DBNull.Value)
                        {
                            DateTime Day = Convert.ToDateTime(obj);
                            if (Day> DateTime.Now.AddDays(-60)) 
                            {
                                e.Appearance.BackColor = Color.Salmon;
                            }
                            
                        }
                    }
                }
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
       
        }

       






    }
}

